import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 * 2, // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'Bearer-' + getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log("请求错误:%o", error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if( res.code == undefined ) {
      return res;
    }
    // if the custom code is not 20000, it is judged as an error.
    if (response.status !== 200) {
      if (response.status == 204) {
        return res;
      }
      return Promise.reject(new Error("错误" || 'Error'))
    } else {
      if (res.code !== 20000) {
        MessageBox.confirm(res.description, '错误', {
          confirmButtonText: '确认',
          type: 'error'
        })
        return Promise.reject(new Error("错误" || 'Error'));
      } else {
        return res
      }
    }
  },
  err => {
    if (err.response.status == 404) {
      Message.error({ message: '请求的资源不存在' });
    } else if (err.response.status == 403) {
      Message.error({ message: '服务器禁止访问,请联系管理员!' });
    } else if (err.response.status == 401) {
      MessageBox.confirm('登录过期，是否重新登录？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          router.push({ path: '/login?redirect=/' })
        })
      }).catch(() => {
        Message.info({ message: "留在当前页面" })
      });
    } else {
      Message.error({
        message: err.response.data.error + ":" +
          err.response.data.message
      });
    }
    return Promise.reject(err);
  }
)

export default service
